import { MenuComponent } from '@/types/interface';

export function pathToCode(path: string) {
  return path.replace('pages/', '').replace('/List.vue', '').replace('.vue', '');
}

export async function components() {
  const schemas = [];
  // 布局组件
  const layouts = import.meta.glob('@/layouts/schema.ts');
  for (const key in layouts) {
    // @ts-ignore
    if (layouts.hasOwnProperty(key)) {
      // @ts-ignore 调用导入函数获取模块内容
      const layout = await layouts[key]();
      let { COMPONENTS } = layout;
      if (!Array.isArray(COMPONENTS)) {
        COMPONENTS = [COMPONENTS];
      }
      for (let i = 0; i < COMPONENTS.length; i++) {
        // @ts-ignore
        const menuComponent: MenuComponent = COMPONENTS[i];
        const component = await menuComponent.component();
        const index = component.default.__file.indexOf('/src/');
        const path = component.default.__file.substring(index + 5);
        schemas.push({
          parentId: '0',
          code: path.replace('.vue', ''),
          path,
          name: menuComponent.name,
          permits: menuComponent.permits,
          elements: [],
        });
      }
    }
  }
  // 页面组件
  const modules = import.meta.glob('@/pages/**/schema.ts');
  for (const key in modules) {
    // @ts-ignore
    if (modules.hasOwnProperty(key)) {
      // @ts-ignore 调用导入函数获取模块内容
      const module = await modules[key]();
      // @ts-ignore 假设每个模块都有一个叫做 myArray 的导出
      let { COMPONENTS } = module;
      if (COMPONENTS) {
        if (!Array.isArray(COMPONENTS)) {
          COMPONENTS = [COMPONENTS];
        }
        for (let i = 0; i < COMPONENTS.length; i++) {
          // @ts-ignore
          const menuComponent: MenuComponent = COMPONENTS[i];
          const component = await menuComponent.component();
          const index = component.default.__file.indexOf('/src/');
          const path = component.default.__file.substring(index + 5);
          const parentCode = menuComponent.code ? menuComponent.code : pathToCode(path);
          schemas.push({
            parentId: '0',
            code: parentCode,
            path,
            name: menuComponent.name,
            elements: menuComponent.elements.map((x) => {
              const code = /^[a-zA-Z0-9].*$/.test(x.code) ? `${parentCode}/${x.code}` : x.code;
              return {
                ...x,
                code,
              };
            }),
            permits: menuComponent.permits,
          });
        }
      }
    }
  }
  console.log(schemas);
  return schemas;
}
